package com.wontube.core.srv;

import java.util.Timer;
import java.util.TimerTask;

import com.wontube.core.srv.schedule.IScheduleService;
import com.wontube.core.srv.time.ITimeService;

/**
 * @author yuechao
 * 
 *         系统服务的诊断服务
 */
public class ServiceWatcher implements IService {
	// 检测的时间间隔
	private static final long PERIOD = ServiceConstants.TIME_SERVICE_INTERVAL * 2;

	// timer
	private Timer timer;

	// 定时任务
	private TheTimerTask task;

	// 启动服务
	@Override
	public void startup() {
		if (this.task != null) {
			this.task.cancel();
		}
		if (this.timer != null) {
			this.timer.cancel();
		}

		// this.lastActionTime = System.currentTimeMillis();
		this.task = new TheTimerTask();
		this.timer = new Timer(false);
		this.timer.schedule(this.task, 5000, PERIOD);
	}

	// 执行诊断
	private void process() {
		// this.lastActionTime = System.currentTimeMillis();
		ServiceManager.diagnose();
	}

	// 关闭服务
	@Override
	public void shutdown() {
		if (this.task != null) {
			this.task.cancel();
			this.task = null;
		}
		
		if (this.timer != null) {
			this.timer.cancel();
			this.timer = null;
		}
	}

	// 是否处于活动状态
	@Override
	public boolean isAlive() {
		// 所有服务都领带于它，它死了也没办法
		return true;
		// return System.currentTimeMillis() - this.lastActionTime < PERIOD * 2;
	}

	// 服务名
	@Override
	public String name() {
		return "ServiceWatcher";
	}

	// 依赖哪些服务, ServiceWatcher 依赖于所有服务，
	// 因为所有服务启动完成后才开始检测
	@Override
	public Class<?>[] depends() {
		return new Class<?>[] { ITimeService.class, IScheduleService.class };
	}

	/**
	 * 定时任务
	 */
	private class TheTimerTask extends TimerTask {
		// 执行诊断
		@Override
		public void run() {
			ServiceWatcher.this.process();
		}
	}
}
